<?php
	
    extract(extractPost(), EXTR_PREFIX_ALL, 'u');
    if(isset($u_name) && isset($u_password) && isset($u_lastname) && isset($u_email) && isset($u_roles)){

        
        // If user id parameter is not set we create new user
        if(!isset($u_user_id)){
            /**
            * Check for an existing user
            */
           $existing_user = R::findOne('user',' email = ? ', 
                                               array( $u_email )
                                              );
           // And return error if user with email exists
           $result = array();
           if($existing_user){
               jsonErrorDie("User email is already in use. Please use another one.");
           }
            /**
            * Create new user.
            */
            $u = R::dispense( 'user' );
            
            $u->active = 1;
            $u->lockTime = null;
            
        }
        // Else load existing one
        else{
            $u = R::load('user', $u_user_id);
            if($u->id == 0){
                jsonErrorDie("This user does not exist.");
            }
            if($u->email != $u_email){
                jsonErrorDie("You cannot change your email. Please contact administrator.");
            }
        }
        
        $u->name = $u_name;
        $u->lastname = $u_lastname;
        $u->email = $u_email;
        $u->password = $u_password;
        
        // Number of days before certain card expires for sending email
        if(isset($u_reminderdays)){
            $u->reminderdays = $u_reminderdays;
        }

        // Adding roles to user
        if(isset($u)){
            // First remove all roles at existing users
            $u->sharedRoleList = array();
            $roles = json_decode($u_roles);
            $roles = R::loadAll('role', $roles);
            foreach($roles as $role){
                $u->sharedRoleList[] = $role;
            }
            R::store($u);

            jsonSuccessDie("user_id", $u->id);
        }
    }
    else{
        jsonErrorDie("Check your parameters. All parameters are mandatory.");
    }
    jsonErrorDie("Problem occured while inserting user in database.");
